package com.elitel.frame.task;

import com.elitel.frame.base.service.CfgDbService;
import com.elitel.frame.base.service.HiveService;
import com.elitel.frame.base.service.KuduService;
import com.elitel.frame.main.entity.CfgDb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component("timeScheduler")
public class TimeScheduler {
    private static final Logger logger = LoggerFactory.getLogger(TimeScheduler.class);
    private final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private CfgDbService cfgDbService;
    @Autowired(required = false)
    private KuduService kuduService;
    @Autowired(required = false)
    private HiveService hiveService;

    @PostConstruct
    public void onStartup() {
        //另起线程进行元数据初始化，避免阻塞服务启动
        new Thread() {
            public void run() {
                try {
                    refreshImpalaTable();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();//开启线程
        logger.info("====================== 定时调度已启动 ====================== " + df.format(new Date()));
    }

    public void refreshImpalaTable() {
        logger.info("======= 开始刷新Impala表元数据信息(refreshImpalaTable)! 时间: " + df.format(System.currentTimeMillis()));
        try {
            List<CfgDb> cfgDbs = cfgDbService.getDbListByDbType("KUDU");
            List<String> allCfgDbs = cfgDbs.stream().map(CfgDb::getDbName).collect(Collectors.toList());
            for (String db : allCfgDbs) {
                List<String> allTables = kuduService.getAllTables(db);
                for (String tablename : allTables) {
                    hiveService.execute("REFRESH " + db + "." + tablename);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("Impala 元数据初始化成功！时间: " + df.format(System.currentTimeMillis()));
    }
}
